package com.ljw.es;

import com.ljw.po.Entity;
import com.ljw.repository.EntityRepository;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: lijunwei
 * @Time: 2019/3/11 22:12
 */
@Service
public class CityESServiceImpl implements CityESService {
    int PAGE_SIZE = 15; //默认分页大小
    int PAGE_NUMBER = 0; //默认当前分页
    String SCORE_MODE_SUM = "sum"; //权重分求和模式
    Float MIN_SCORE = 10.0F; //由于无相关性的分值默认为1， 设置权重分最小值为10
    @Autowired
    EntityRepository entityRepository;

    /**
     * 保存内容到ES
     */
    @Override
    public Long saveEntity(Entity entity) {
        Entity entityResult = entityRepository.save(entity);
        return entityResult.getId();
    }

    /**
     * 在ES中搜索内容
     */
    @Override
    public List<Entity> searchEntity(int pageNumber, int pageSize, String searchContent) {

        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "ljw01003");
        //设置分页，否则只能按照ES默认的分页给
        Pageable pageable = new PageRequest(0, 15);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(matchQueryBuilder).build();

        System.out.println("\n searchCity: searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

        Page<Entity> cityPage = entityRepository.search(searchQuery);
        return cityPage.getContent();
    }



}
